package com.edu.homework;

import javax.xml.crypto.Data;
import java.math.BigDecimal;

/**
 * 两个用户取钱，没人取200，不能超取
 */
public class HomeWork02 {

    public static void main(String[] args) {
//        Object lock = new Object();
//        new T(lock).start();
//        new T(lock).start();

        DataSource dataSource = new DataSource();
        new Thread(dataSource).start();
        new Thread(dataSource).start();
    }


}

class T extends Thread {
    private volatile double total = 10000;

    Object lock;

    public T(Object lock) {
        this.lock = lock;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (lock) {
                if (total == 0){
                    return;
                }
                System.out.println(Thread.currentThread().getName() + "取了 1000");
                total = total - 1000;
                System.out.println("剩余" + total);

            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class DataSource implements Runnable {
    private double total = 10000;

    @Override
    public void run() {
        while (true){
            synchronized (this){
                if (total == 0){
                    return;
                }
                System.out.println(Thread.currentThread().getName() + "取了 1000");
                total = total - 1000;
                System.out.println("剩余" + total);
            }
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}